const bcrypt = require("bcryptjs");
const { getUserInfo } = require("../../services/admin/user.service");
const {
  userFomateError,
  userAlreadyExited,
  userRegisterError,
  userDoesNotExist,
  userLoginError,
  invalidPassord,
  addUserFomateError,
} = require("../../constant/err.type");
const userValidator = async (ctx, next) => {
  const { user_name, password } = ctx.request.body;
  //合法性
  if (!user_name || !password) {
    console.error("用户名或密码为空", ctx.request.body);
    ctx.app.emit("error", userFomateError, ctx);
    return;
  }

  await next();
};

const addUserValidator = async (ctx, next) => {
  const { user_name, password, is_admin, introduction, avatar } =
    ctx.request.body;
  //合法性
  if (!user_name || !password || !is_admin || !introduction || !avatar) {
    console.error("添加用户包含信息不能为空", ctx.request.body);
    ctx.app.emit("error", addUserFomateError, ctx);
    return;
  }

  await next();
};

const verifyUser = async (ctx, next) => {
  const { user_name } = ctx.request.body;
  //合理性
  // if (await getUserInfo({ user_name })) {
  //   ctx.app.emit("error", userAlreadyExited, ctx);
  //   return;
  // }
  try {
    const res = await getUserInfo({ user_name });
    if (res) {
      console.error("用户名已经存在", { user_name }); //记录到服务器的日志上
      ctx.app.emit("error", userAlreadyExited, ctx);
      return;
    }
  } catch (err) {
    console.error("获取用户信息出错", err);
    ctx.app.emit("error", userRegisterError, ctx);
    return;
  }
  await next();
};

const cryptPassword = async (ctx, next) => {
  const { password } = ctx.request.body;

  const salt = bcrypt.genSaltSync(10);
  //hash保存的是密文
  const hash = bcrypt.hashSync(password, salt);
  ctx.request.body.password = hash;

  await next();
};

const verifyLogin = async (ctx, next) => {
  try {
    //判断用户是否存在
    const { user_name, password } = ctx.request.body;
    const res = await getUserInfo({ user_name });
    if (!res) {
      console.error("用户名不存在", { user_name });
      ctx.app.emit("error", userDoesNotExist, ctx);
      return;
    }
    //判断密码是否匹配（不匹配:报错）
    if (!bcrypt.compareSync(password, res.password)) {
      ctx.app.emit("error", invalidPassord, ctx);
      return;
    }
  } catch (error) {
    console.error(err);
    ctx.app.emit("error", userLoginError, ctx);
    return;
  }

  await next();
};

module.exports = {
  userValidator,
  verifyUser,
  cryptPassword,
  verifyLogin,
  addUserValidator,
};
